﻿using KwaiXiaoDian.Entity.Common;
using KwaiXiaoDian.Entity.DO;
using KwaiXiaoDian.Entity.VO.Product;
using KwaiXiaoDian.Entity.VO.Notice;
using KwaiXiaoDian.IDao;
using KwaiXiaoDian.IService;
using Microsoft.Extensions.Logging;
using SSharing.Frameworks.NetCore.Common.Extends;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Microsoft.Extensions.Configuration;
using SSharing.Frameworks.NetCore.Common.Results;
using SSharing.Frameworks.NetCore.Common.Consts;
using System.Diagnostics;
using Microsoft.Extensions.Caching.Memory;

namespace KwaiXiaoDian.Service
{
    /// <summary>
    /// 商品达人排行榜信息service
    /// </summary>
    public class ProductRankService : BaseService<TProductRank>, IProductRankService
    {
        private readonly IProductRankDao _productRankDao;
        private readonly IKwaiXiaoDianService _kwaiXiaoDianService;
        private readonly ILogger<ProductRankService> _logger;
        private readonly IConfiguration _configuration;
        private readonly IMemoryCache _memoryCache;

        public ProductRankService(IProductRankDao productRankDao
            , IKwaiXiaoDianService kwaiXiaoDianService
            , ILogger<ProductRankService> logger
            , IConfiguration configuration
            , IMemoryCache memoryCache) : base(productRankDao)
        {
            _productRankDao = productRankDao;
            _kwaiXiaoDianService = kwaiXiaoDianService;
            _logger = logger;
            _configuration = configuration;
            _memoryCache = memoryCache;
        }

        /// <summary>
        /// 获取商品达人排行榜
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public IPagingResult<Rank> GetPagingRanks(GetPagingRanksRequest request)
        {
            List<Rank> list = new List<Rank>();
            IPagingResult<Rank> pagedRanks = new PagingResult<Rank>(0, request.Page, request.Limit, list);

            //读取缓存
            var cacheRankHours = _configuration["Cache.Rank.Hours"].ToInt(24);
            var cacheKey = string.Format("KwaiXiaoDian:Product:Rank:{0}", request.ProductId);
            var cacheValue = _memoryCache.Get(cacheKey);
            if (cacheValue != null)
            {
                pagedRanks = (IPagingResult<Rank>)cacheValue;
                return pagedRanks;
            }

            //优行从商品达人排行榜接口（包含缓存）获取，获取后直接返回不需要落地
            var getProductRankInfoResult = _kwaiXiaoDianService.GetProductRankInfo(request.DistributeItemId, request.ProductId);
            if (!getProductRankInfoResult.IsSuccess)
            {
                //记录日志
                _logger.LogError(string.Format("获取商品达人排行榜时发生异常，Message：{0}", getProductRankInfoResult.ErrorMessage));
                return new PagingResult<Rank>(0, request.Page, request.Limit, list);
            }

            if (getProductRankInfoResult.Data.HasValue())
            {
                foreach (var item in getProductRankInfoResult.Data)
                {
                    list.Add(new Rank
                    {
                        //Id = item.Id,
                        CreatedTime = item.CreatedTime.ToString(DateTimeTypeConst.DATETIME),
                        Ranking = item.Rank.HasValue ? item.Rank.Value : 0,
                        AuthorId = item.AuthorId,
                        AuthorName = item.AuthorName,
                        AuthorHeadImg = item.AuthorHeadImg
                    });
                }
                pagedRanks = list.OrderBy(p => p.Ranking).AsQueryable<Rank>().Paging<Rank>(request.Page, request.Limit);
            }

            //设置缓存，无数据也需要缓存
            _memoryCache.Set(cacheKey, pagedRanks, DateTimeOffset.Now.AddHours(cacheRankHours));

            return pagedRanks;
        }

    }
}
